package bean;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class LoginCheck implements PhaseListener {

	private static final long serialVersionUID = 1L;

	public LoginCheck() {
	}

	@Override
	public void afterPhase(PhaseEvent arg0) {
        FacesContext fc = arg0.getFacesContext();

        // Check to see if they are on the login page.
        boolean loginPage =
	  fc.getViewRoot().getViewId().lastIndexOf("login") > -1 ? true : false;
        if (!loginPage && !loggedIn()) {
            NavigationHandler nh = fc.getApplication().getNavigationHandler();
            nh.handleNavigation(fc, null, "logout");
        }

	}

	@Override
	public void beforePhase(PhaseEvent arg0) {

	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
	
    private boolean loggedIn() {
        return LoginBean.isLogged();
    }

}
